package com.xiaodoo.http.auto;

import com.xiaodoo.http.anno.EnableHttpClient;
import com.xiaodoo.http.handler.HttpClientInvocationHandler;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * 作者： zhi-liao
 * 类的作用:
 * 类的创建时间： 2021/7/31 18:52
 */
public class HttpClientRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
        System.out.println("===HttpClientRegister===");
        Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(EnableHttpClient.class.getName());
        System.out.println(attributes);
        Class<?>[] classes = (Class<?>[]) attributes.get("classes");
        Object proxyBean = Proxy.newProxyInstance(HttpClientRegister.class.getClassLoader(),
                classes,
                new HttpClientInvocationHandler());
        System.out.println("proxyBean1:"+proxyBean.getClass());
        // 通过BeanDefinition注册Bean
        BeanDefinitionBuilder beanDefinitionBuilder =
                BeanDefinitionBuilder.genericBeanDefinition(proxyBean.getClass());
        beanDefinitionBuilder.addConstructorArgValue(new HttpClientInvocationHandler());
//        beanDefinitionBuilder.addConstructorArgValue(classes);
//        beanDefinitionBuilder.addConstructorArgValue(proxyBean);
        BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();

        registry.registerBeanDefinition("ipLocationClient", beanDefinition);
        System.out.println("proxyBean1:"+registry.getBeanDefinition("ipLocationClient").getBeanClassName());
    }
    private static class JdHttpClientClassFactoryBean implements FactoryBean {

        private final Class<?> jdHttpClientClass;

        private final Object proxy;

        private JdHttpClientClassFactoryBean(Class<?> jdHttpClientClass, Object proxy) {
            this.jdHttpClientClass = jdHttpClientClass;
            this.proxy = proxy;
        }

        @Override
        public Object getObject() throws Exception {
            return proxy;
        }

        @Override
        public Class<?> getObjectType() {
            return jdHttpClientClass;
        }
    }
}
